package com.liesheng.haylou.ui.personal;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Message;
import android.os.StrictMode;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.alibaba.idst.nls.internal.utils.L;
import com.liesheng.haylou.R;
import com.liesheng.haylou.base.BaseActivity;
import com.liesheng.haylou.base.BaseFunActivity;
import com.liesheng.haylou.base.BaseResult;
import com.liesheng.haylou.base.BaseVm;
import com.liesheng.haylou.bean.NickNameBean;
import com.liesheng.haylou.bean.UploaddBean;
import com.liesheng.haylou.bean.UserUpdateBean;
import com.liesheng.haylou.common.GlideHelper;
import com.liesheng.haylou.databinding.ActivityPersonalDataSettingBinding;
import com.liesheng.haylou.db.DBManager;
import com.liesheng.haylou.net.HttpCallback;
import com.liesheng.haylou.net.HttpRequest;
import com.liesheng.haylou.utils.ToastUtil;
import com.liesheng.haylou.utils.UploadUtil;
import com.liesheng.haylou.utils.sp.SpUtil;
import com.liesheng.haylou.view.dialog.NickDialog;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import androidx.core.app.ActivityCompat;
import androidx.databinding.DataBindingUtil;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

public class PersonalDataSettingActivity extends BaseActivity<ActivityPersonalDataSettingBinding, BaseVm> implements UploadUtil.OnUploadProcessListener {
    /**
     * 判断的标识
     */
    //需要的权限数组 读/写/相机
    private static String[] PERMISSIONS_STORAGE = {Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
    private static final int PHOTO_REQUEST = 1;
    private static final int CAMERA_REQUEST = 2;
    private static final int PHOTO_CLIP = 3;
    private static final int UPLOAD_INIT_PROCESS = 4;//上传初始化
    protected static final int UPLOAD_FILE_DONE = 2;//上传中
    private static final int UPLOAD_IN_PROCESS = 5;//上传文件响应
    private File filepath;//返回的文件地址
    private AlertDialog.Builder builder;
    private LayoutInflater inflater;
    private AlertDialog dialog;
    private View layout;
    private Dialog mShareDialog;
    private String showNickName;
    private static final int REQUEST_CODE_CHOOSE = 1001;

    @Override
    protected ActivityPersonalDataSettingBinding getmBinding() {
        mBinding = DataBindingUtil.inflate(getLayoutInflater(), R.layout.activity_personal_data_setting, null, false);
        //隐藏掉整个ActionBar
        //跳转相机动态权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
            StrictMode.setVmPolicy(builder.build());
        }
        return mBinding;
    }

    @Override
    protected BaseVm getViewModel() {
        return null;
    }

    @Override
    protected void initData() {
        setTitle("个人资料设置");
        UserInfo();
    }

    public static void startBy(BaseFunActivity activity) {
        Intent intent = new Intent(activity, PersonalDataSettingActivity.class);
        activity.startActivity(intent);
    }



    @Override
    public void onClickView(View view) {
        switch (view.getId()) {
            case R.id.rlHeadlerName:
                viewHeader();
                break;
            case R.id.photograph:
                //检查是否已经获得相机的权限
                if (verifyPermissions(PersonalDataSettingActivity.this, PERMISSIONS_STORAGE[2]) == 0) {
                    L.e("提示是否要授权");
                    ActivityCompat.requestPermissions(PersonalDataSettingActivity.this, PERMISSIONS_STORAGE, 3);
                } else {
                    //已经有权限
                    getCamera();  //打开相机
                }
                break;
            case R.id.photo:
               // getPhoto();
                choosePhoto();
                break;
            case R.id.cancel:
                dialog.dismiss();
                break;
            case R.id.tvNickName:
                showNickName();
                break;
            case R.id.tvGender:
                SelectGender();
                break;
        }
    }
    private void choosePhoto() {
        Matisse.from(this)
                .choose(MimeType.ofImage())
                .countable(true)
                .maxSelectable(1)
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                .thumbnailScale(0.85f)
                .imageEngine(new GlideEngine())
                .showPreview(false) // Default is `true`
                .forResult(REQUEST_CODE_CHOOSE);
    }

    private void showNickName() {
        NickDialog dialog = new NickDialog(PersonalDataSettingActivity.this,
                new NickDialog.OnEditInputFinishedListener() {
                    @Override
                    public void editInputFinished(String nickName) {
                        showNickName = nickName;
                        mBinding.tvNickName.setText(showNickName);
                        UserUpdate();
                    }
                });
        Window window = dialog.getWindow();
        window.setGravity(Gravity.BOTTOM);
        dialog.setView(new EditText(PersonalDataSettingActivity.this));  //若对话框无法弹出输入法，加上这句话
        dialog.show();
    }

    /**
     * 从系统相机选择图片来源
     */
    private void getCamera() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(
                Environment.getExternalStorageDirectory(), "fileImg.jpg")));
        startActivityForResult(intent, CAMERA_REQUEST);

    }

    /**
     * 检查是否有对应权限
     *
     * @param activity   上下文
     * @param permission 要检查的权限
     * @return 结果标识
     */
    public int verifyPermissions(Activity activity, java.lang.String permission) {
        int Permission = ActivityCompat.checkSelfPermission(activity, permission);
        if (Permission == PackageManager.PERMISSION_GRANTED) {
            return 1;
        } else {
            return 0;
        }
    }
    private void uploadPhoto(List<String> filepath) {
        List<File> files = new ArrayList<>();
        MultipartBody.Builder builder = new MultipartBody.Builder();
        if (filepath != null && filepath.size() > 0) {
            for (int i = 0; i < filepath.size(); i++) {
                files.add(new File(filepath.get(i)));
            }
        }
        if (files != null && files.size() > 0) {
            for (File file : files) {
                builder.addFormDataPart("file", file.getName(), RequestBody.create(MediaType.parse("files/*"), file));
            }
        }
        //单张上传
        MultipartBody multipartBody = builder.build();
        requestHttp(buildHttpService().getUploaddFile(multipartBody), new HttpCallback<UploaddBean>() {
            @Override
            public void onNext(UploaddBean uploaddBean) {
                if (null != uploaddBean && uploaddBean.getCode() == 200) {
                    if(uploaddBean.getData() != null){
                        SpUtil.saveAvatar(uploaddBean.getData().getFilePath());
                        GlideHelper.loadCicleImage(mBinding.ivHeader,"http://ls-app-file.haylou.com/"+ SpUtil.getAvatar());
                    }
                }
            }
        });
    }

    /**
     * 上传服务器响应回调
     */
    @Override
    public void onUploadDone(int responseCode, String message) {
        //上传完成响应
        Message msg = Message.obtain();
        msg.what = UPLOAD_FILE_DONE;
        msg.arg1 = responseCode;
        msg.obj = message;
    }

    @Override
    public void onUploadProcess(int uploadSize) {
        //上传中
        Message msg = Message.obtain();
        msg.what = UPLOAD_IN_PROCESS;
        msg.arg1 = uploadSize;
    }

    @Override
    public void initUpload(int fileSize) {
        //准备上传
        Message msg = Message.obtain();
        msg.what = UPLOAD_INIT_PROCESS;
        msg.arg1 = fileSize;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_CHOOSE && resultCode == RESULT_OK) {
            //图片路径 同样视频地址也是这个 根据requestCode
            uploadPhoto(Matisse.obtainPathResult(data));
        }
    }
    private void SelectGender() {
        mShareDialog = new Dialog(this, R.style.dialog_bottom_full);
        mShareDialog.setCanceledOnTouchOutside(true);
        mShareDialog.setCancelable(true);
        Window window = mShareDialog.getWindow();
        window.setGravity(Gravity.BOTTOM);
        View view = View.inflate(this, R.layout.lay_share, null);
        TextView tvOk = view.findViewById(R.id.tvOk);
        RadioGroup radgroup = view.findViewById(R.id.radioGroup);
        tvOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                for (int i = 0; i < radgroup.getChildCount(); i++) {
                    RadioButton rd = (RadioButton) radgroup.getChildAt(i);
                    if (rd.isChecked()) {
                        mBinding.tvGender.setText(rd.getText());
                        break;
                    } else {
                        mShareDialog.dismiss();
                    }
                }
            }
        });
        window.setContentView(view);
        window.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);//设置横向全屏
        mShareDialog.show();
    }

    private void viewHeader() {
        builder = new AlertDialog.Builder(this);
        inflater = getLayoutInflater();
        layout = inflater.inflate(R.layout.dialog_select_photo, null);
        builder.setView(layout);//设置对话框的布局
        dialog = builder.create();//生成最终的对话框
        Window window = dialog.getWindow();
        window.setWindowAnimations(R.style.dialog_bottom_full);
        window.setGravity(Gravity.BOTTOM);
        dialog.show();//显示对话框

    }

    private void UserUpdate() {
        Map<String, Object> map = new HashMap<>();
        map.put("nickName", showNickName);
        requestHttp(buildHttpService().getUserUpdate(HttpRequest.getBody(map)), new HttpCallback<NickNameBean>() {
            @Override
            public void onNext(NickNameBean nickNameBean) {
                if( nickNameBean!= null){
                        if(nickNameBean.getData() != null){
                            SpUtil.saveNickName(nickNameBean.getData().getNickName());
                            mBinding.tvNickName.setText(SpUtil.getNickName());
                        }
                }
            }
        });
    }

    /**
     * 获取用户信息
     */
    private void UserInfo() {
        requestHttp(buildHttpService().getUserInfo(), new HttpCallback<UserUpdateBean>() {
            @Override
            public void onNext(UserUpdateBean userUpdateBean) {
                if (null != userUpdateBean) {
                    if (userUpdateBean.getCode() == 200) {
                        if(userUpdateBean.getData() != null){
                            SpUtil.saveUserInfo(userUpdateBean);
                            SpUtil.saveNickName(userUpdateBean.getData().getNickName());
                            SpUtil.saveAvatar(userUpdateBean.getData().getAvatar());
                        }

                    }
                }
            }
        });
    }
}
